'use strict';
import Base from './base.js';

export default class extends Base {

	// 充值单列表
	async rechargelistAction(){
		let page = JSON.parse(this.post('page'));
		/*let zt = page.zt*1?[0]:[1,2];*/		
		let zt = page.zt;		
		let shopid = this.shop_userinfo.departmentid;
		let where = {
			's.departmentid':shopid,
			's.ordertype':3, 
			'g.name|g.vipcard|a.name|z.name|g.phone|s.remarks':['like','%'+page.search+'%']
		}
		if (page.zt != 3) {
			where['s.status'] = page.zt 
		}

		//设置时间
		if (page.times && (page.times[0] != null && page.times[1] != null)) {
			let begintime = Math.floor(new Date(page.times[0]).setHours(0,0,0,0)/1000)
			let endtime = Math.floor(new Date(page.times[1]).setHours(0,0,0,0)/1000) + 86400
			where['s.addtime'] = {'>=': begintime, '<': endtime}
 		}
		
		let list = await this.model('or_shop_order')
				.alias('s')
				.join('think_or_guest g on s.guestid = g.id')
				.join('`think_or_department` d on g.departmentid = d.id')
				.join('think_or_admin a on s.operatorid = a.id')
				.join('think_or_admin z on s.auditorid = z.id')
				.join('think_or_shop_orderinfo oi on oi.orderid = s.id and oi.type=5')
				.field('s.*,g.name as gname,g.phone as gphone,g.vipcard,a.name as aname,z.name as zname,oi.price,d.name as shopname')
				.where(where)
				.page(page.pages, page.limits)
				.order('s.addtime desc')
				.countSelect();
		
		return this.json(list);
	}

	// 获取客户的充值卡及信息
	async guestbalanceinfoAction(){
		let guestid = this.post('id');
		let data = await this.model('or_shop_order')
				.alias('o')
				.field('oi.type,oi.typename,oi.num,oi.price,oi.orderid,o.addtime')
				.join('`think_or_shop_orderinfo` oi on oi.orderid=o.id')
				.where({'o.guestid':guestid,'o.ordertype':3})
				.select();
		return this.json(data);
	}

	// 删除充值单
	async deleterechargeorderAction(){
		let id = this.post('id');
		/*
		* 1、第一步先判断当前订单是否已删除
		* 2、判断当前订单是否已经结账或者审核
		*/
		let isdel = await this.model('or_shop_order').where({id:id, status:0}).find();
		if (think.isEmpty(isdel)) {
			return this.fail('该订单已结账或已删除');
		}
		// 删除订单表和订单附属表
		let model = this.model('or_shop_order');
		await model.transaction(async()=> {
			try{
				let resorder = await model.where({id:id}).delete();
				let resorderinfo = await this.model('or_shop_orderinfo').db(model.db()).where({orderid:id}).delete();
				if (!resorder && !resorderinfo) {
					await model.rollback();
					return this.fail('删除失败');
				}
				await model.commit();
				return this.success("删除成功");
			}catch(e){
				await model.rollback();
				return this.fail("删除失败");
			}
		})
	}

	// 当前客户充值及消费信息
	async viewrechargeinfoAction(){
		if (this.isGet) {
			let id = this.get('id');
			let order = await this.model('or_shop_order').where({id:id}).find();
			let ginfo = await this.model('or_guest').where({id:order.guestid}).field('name,phone').find();
			let cinfo = await this.model('or_shop_orderinfo')
									.alias('o')
									.join('`think_or_shop_guestcard` c on c.id = o.guestcardid')
									.where({'o.orderid':id})
									.select();
			let ainfo = await this.model('or_shop_accountlog')
									.alias('l')
									.field('l.accountid, l.money, a.name, a.accountsn, a.accounttype')
									.join('`think_or_shop_account` a on a.id = l.accountid')
									.where({'l.orderid':id})
									.select();
			let uinfo = await this.model('or_shop_yejixianjin')
									.alias('xj')
									.field('xj.feat, u.name, u.username, p.name as zhicheng')
									.join('`think_or_app_user` u on u.id = xj.userid')
									.join('`think_or_position` p on p.id = u.zhichengid')
									.where({'xj.orderid':id})
									.select();

			let data = {
				oinfo : order,
				ginfo : ginfo,
				cinfo : cinfo,
				ainfo : ainfo,
				uinfo : uinfo,
			}
			return this.json(data);
		} else {
			let id = this.post('id');
			let ischeck = await this.model('or_shop_order').where({id:id}).find();
			if (ischeck.status == 2) {
				return this.fail('该订单已审核');
			}
			let res = await this.model('or_shop_order').where({id:id}).update({'status':2, 'auditorid':this.shop_userinfo.id});
			return res?this.success({info:'审核成功'}):this.fail('审核失败');
		}
	}

	// 获取当前充值订单信息
	async getrechargeinfoAction(){
		let orderid = this.post('orderid');

		let shopid = this.shop_userinfo.departmentid;

		let oinfo = await this.model().query('select * from `think_or_shop_orderinfo` where orderid='+orderid);

		let ginfo = await this.model('or_guest')
					.alias('g')
					.field('g.*,b.name as cardname')
					.join('`think_or_shop_order` o on o.guestid=g.id')
					.join('`think_or_shop_accountlog` a on a.orderid=o.id')
					.join('`think_or_shop_account` b on b.id= a.accountid')
					.where({'o.id': orderid})
					.select();

		let ulist = await this.model('or_shop_yejiticheng')
				.alias('yj')
				.field('yj.id, yj.userid, yj.xianjinyeji, u.name, u.worknum, u.bumenid,u.xiaozuid')
				.join('`think_or_app_user` u on u.id=yj.userid')
				.where({'yj.orderid': orderid, 'yj.shopid': shopid, 'yj.ordertype': 'CZD'})
				.select();

		let data = {
			oinfo: oinfo,
			ginfo: ginfo,
			ulist: ulist,
		}

		return this.json(data)
	}

	// 获取充值单信息
	async rechargeinfoAction(){
		let guestid = this.post('guestid');
		let orderid = this.post('orderid');
		let shopid = this.shop_userinfo.departmentid;

		let order = await this.model('or_shop_order').where({id:orderid}).find();
		let oinfo = await this.model('or_shop_orderinfo').where({orderid:orderid}).select();
		let ginfo = await this.model('or_guest').where({id:guestid}).find();
		let viplist = await this.model('or_department')
				.alias('d')
				.field('v.*')
				.join('`think_or_guest_vipgrade` v on v.departmentid=d.pid or v.departmentid=0')
				.where({'d.id': shopid})
				.select();

		let data = {
			isjz : order.status,
			oinfo: oinfo,
			ginfo: ginfo,
			vips: viplist
		}
		return this.json(data);
	}

	// 充值反结账
	async fanpayAction () {
		let id = this.post('id')

		// 判断状态是否满足
		let oinfo = await this.model('or_shop_order').where({id: id}).find()

		let isCanEditOrder = await this.isCanEditOrder(id, 'CZD')
		if (!isCanEditOrder) {
			return this.fail('暂不允许操作其他店单据！')
		}
		// 判断订单状态
		if (oinfo.status != 1) {
			return this.fail('该单据未结账或已经分配业绩')
		}

		let shopid = this.shop_userinfo.departmentid;

		let model = this.model('or_shop_order');
		await model.transaction(async ()=>{
			try {
				/*
				* 收款账户循环返还金额，删除日志
				* 减去客户的账户金额和产生的积分，删除个人账户日志记录和积分产生记录
				* 减去现金业绩日志
				* 有赠送产品增加库存，删除库存日志
				* 有暂存的删除暂存信息
				*/

				// 收款账户日志查找
				let accountlog = await this.model('or_shop_accountlog').db(model.db()).where({ordertype: 'CZD', orderid: id}).select()

				let resaccount = 1, resaccountlog = 1;

				if (accountlog.length > 0) {
					let accountlist = []
					for (var i = accountlog.length - 1; i >= 0; i--) {
						let account = await this.model('or_shop_account').db(model.db()).where({id: accountlog[i].accountid}).find();

						account.balance -= Number(accountlog[i].money);

						accountlist.push(account)
					}
					resaccount = await this.model('or_shop_account').db(model.db()).updateMany(accountlist);

					resaccountlog = await this.model('or_shop_accountlog').db(model.db()).where({ordertype: 'CZD', orderid: id}).delete()
				}

				// 找出客户账户日志
				// 判断是否有积分赠送，如果有则返还积分并删除积分日志
				let guestaccountlog = await this.model('or_shop_guest_accountlog').db(model.db()).where({ordertype: 'CZD', orderid: id}).find()

				let resguestaccount = 1,resguestaccountlog = 1;

				if (guestaccountlog.balance != 0 || guestaccountlog.giftbalance != 0) {
					let guest = await this.model('or_guest').db(model.db()).where({id:guestaccountlog.guestid}).find()

					let integralLog = await this.model('or_shop_jifenlog').db(model.db()).where({shopid: shopid, type: 3, orderid: id}).find();

					let gengxinGuestYuE = {
						balance: guest.balance - Number(guestaccountlog.balance),
						giftbalance: guest.giftbalance - Number(guestaccountlog.giftbalance)
					}

					if (!think.isEmpty(integralLog)) {
						gengxinGuestYuE.score = guest.score - Number(integralLog.jifen);
						let delJifenLog = await this.model('or_shop_jifenlog').db(model.db()).where({shopid: shopid, type: 3, orderid: id}).delete();
						if (!delJifenLog) {
							await model.rollback();
							return this.fail('返还积分失败');
						}
					}

					resguestaccount = await this.model('or_guest').db(model.db()).where({id: guestaccountlog.guestid}).update(gengxinGuestYuE);

					resguestaccountlog = await this.model('or_shop_guest_accountlog').db(model.db()).where({ordertype: 'CZD', orderid: id}).delete()
				}

				// 查看商品日志
				let goodslog = await this.model('or_shop_goodslog').db(model.db()).where({orderid:id,ordertype: 'CZD'}).select()

				let resgoods = 1, resgoodslog = 1
				if (goodslog.length > 0) {

					let goodsdata = []
					for (var i = goodslog.length - 1; i >= 0; i--) {
						let goods = await this.model('or_shop_goods').db(model.db()).where({goodsid: goodslog[i].goodsid, shopid: shopid}).find()
						goods.nums -= Number(goodslog[i].nums)
						goodsdata.push(goods)
					}
					resgoods = await this.model('or_shop_goods').db(model.db()).updateMany(goodsdata)
					resgoodslog = await this.model('or_shop_goodslog').db(model.db()).where({orderid:id,ordertype: 'CZD'}).delete()

				}

				// 删除暂存的信息
				let reszancun = await this.model('or_shop_guest_temp_reserve').db(model.db()).where({orderid: id}).delete();

				// 删除客户卡项表赠送的项目
				let reskxsub = await this.model('or_shop_guestcardsubject').db(model.db()).where({shopid: shopid, orderid: id}).delete();

				// 除去现金业绩
				let resxianjin = await this.model('or_shop_yejixianjin').db(model.db()).where({feattype: 'CZD', orderid: id}).select();

				let resticheng = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, ordertype: 'CZD', orderid: id}).select();

				if (resxianjin.length && resticheng.length) {

					let del_yejis = await this.model('or_shop_yejixianjin').db(model.db()).where({orderid: id}).delete();

					let del_tichengs = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, ordertype: 'CZD', orderid: id}).delete();

					if (!del_yejis && !del_tichengs) {
						await model.rollback();
						return this.fail('清除现金业绩失败');
					}

				}

				// 更改单据信息
				let resorder = await model.where({id:id}).update({status: 0,auditorid: 0})

				if (resaccount && resaccountlog && resguestaccount && resguestaccountlog && resgoods && resgoodslog && reszancun !== false && reskxsub !== false && resorder) {
					await model.commit();
					return this.success({code: 200, info: '反结账成功', status: 0});
				} else {
					await model.rollback();
					return this.fail('反结账失败');
				}

			} catch (e) {
				console.log(e);
				await model.rollback();
				return this.fail('反结账失败');
			}
		})
	}

	// 获取机构会员等级
	async getvipgradeAction(){
		let shopid = this.shop_userinfo.departmentid;
		let viplist = await this.model('or_department')
				.alias('d')
				.field('v.*')
				.join('`think_or_guest_vipgrade` v on v.departmentid=d.pid or v.departmentid=0')
				.where({'d.id': shopid})
				.select();
		return this.json(viplist);
	}

	// query shop guest of remote
	async queryguestlistAction(){
		let query = this.get('query');
		let shopid = this.shop_userinfo.departmentid;

		let orid = await this.model('or_department').where({id: shopid}).getField('pid', true);

		let shoplist = await this.model('or_department')
				.alias('s')
				.join('`think_or_department` d on d.id=s.pid')
				.where({'s.pid': orid})
				.getField('s.id');

		let list = await this.model('or_guest')
				.alias('g')
				.field('g.*,v.vipname')
				.join('`think_or_guest_vipgrade` v on v.id=g.level')
				.where('g.departmentid IN ('+shoplist+') AND g.initial_info = 1 AND (g.vipcard LIKE "'+query+'" OR g.phone LIKE "'+query+'")')
				.select();
				
		return this.json(list);
	}

	// 客户欠款列表
	async debtlistAction(){
		/*let pages = this.post('pages');
		let limits = this.post('limits');
		let search = this.post('search');*/
		let page = JSON.parse(this.post('page'));
		let where ={
			departmentid:this.shop_userinfo.departmentid,
			balance:['<',0], 
			'name|phone|vipcard': ['like', '%'+page.search+'%']
		}
		let list = await this.model('or_guest')
		.where(where)
		.page(page.currentSize, page.pageSize)
		.countSelect();
		return this.json(list);
	}

	// 获取当前未结账订单信息
	async getguestinfoAction(){
		let oid = this.post('oid');

		let oinfo = await this.model('or_shop_order').where({id: oid}).find();

		let olist = await this.model('or_shop_orderinfo').where({orderid: oid}).select();

		let ginfo = await this.model('or_shop_order')
				.alias('o')
				.field('g.*')
				.join('`think_or_guest` g on g.id=o.guestid')
				.where({'o.id':oid})
				.find();

		let data = {
			oinfo: oinfo,
			olist: olist,
			ginfo: ginfo
		}

		return this.json(data);
	}

	async getguestAction(){
		let gid = this.get('gid');
		let ginfo = await this.model('or_guest').where({id: gid}).find();
		return this.json(ginfo);
	}

	async getjisuantichengAction () {
		let id = this.post('id')
		// 列出订单信息
		let  orderlist = await this.model('or_shop_orderinfo').where({orderid: id}).select()

		let orderinfo = await this.model('or_shop_order').where({id: id}).find()
		
		let fenpeilist = await this.model('or_shop_yejiticheng')
				.alias('y')
				.field('y.*, u.name')
				.join('left join `think_or_app_user` u on y.userid = u.id')
				.where({'y.ordertype': 'CZD', 'y.orderid': id})
				.select()

		let data = {
			orderlist: orderlist,
			fenpeilist: fenpeilist,
			orderinfo: orderinfo
		}
		return this.json(data)
	} 

	// 根据tp判断当前get的是产品还是项目
	async getalllistAction(){

		let shopid = this.shop_userinfo.departmentid;

		let goods = await this.model('or_shop_goods')
			.alias('s')
			.field('s.*,g.id as pxid,g.name,g.number,IFNULL(null, 1) as type,g.brandid')
			.join('`think_or_goods` g on g.id=s.goodsid')
			.where({'s.shopid': shopid, 's.isdisable': 0})
			.select();

		let subject = await this.model('or_shop_subject')
			.alias('s')
			.field('s.*,g.id as pxid, g.name,g.number,IFNULL(null, 2) as type,g.brandid')
			.join('`think_or_subject` g on g.id=s.subjectid')
			.where({'s.shopid': shopid, 's.isdisable': 0})
			.select();

		let alist = await this.model('or_shop_account').where({departmentid: shopid, isdisable: 0}).select();

		let ulist = await this.model('or_app_user').where({shopid: shopid, isdisable: 0}).select();

		let basis = await this.model('or_shop_basis').where({shopid: shopid}).find();

		let data = {
			goods: goods,
			subject: subject,
			alist: alist,
			ulist: ulist,
			basis: basis
		}

		return this.json(data);
	}

	// 最新测试版充值（开单，结账，分配于一体）
	async newchongzhiAction(){
		let data = JSON.parse(this.post('retData'));

		let shopid = this.shop_userinfo.departmentid;

		let aid = this.shop_userinfo.id;

		let nowTime = Math.round(Date.now()/1000);

		// 获取当前分店基础设置
		let basis = await this.model('or_shop_basis').where({shopid: shopid}).find();

		let ordersn = await this.getordersn('CZD',1);

		let model = this.model('or_shop_order');

		await model.transaction(async () =>{

			try {

				/**************************************************************
				 * 1、先写入：or_shop_order表，获取orderid
				 * 2、根据orderid写入：or_shop_orderinfo表
				 * 3、记录客户账户余额充值记录：or_shop_guest_accountlog
				 * 4、然后更新客户信息：or_guest（balance，giftalance，level，arrivetime，score）
				 * 5、根据充值金额balance记录客户积分日志：or_shop_jifenlog
				 * 6、如果有赠送的产品或项目，则记录到对应的表里
				 * 		-> 项目：or_shop_guestcardsubject
				 * 		-> 产品：or_shop_guest_temp_reserve
				 * 7、如果有产品，则减去相应库存：or_shop_goods
				 * 8、并记录减去的库存记录：or_shop_goodslog
				 * 9、如果有收款账户，则增加账户余额：or_shop_account
				 * 10、并且记录账户余额增加记录：or_shop_accountlog
				 * 11、如果有业绩分配，则写入：or_shop_yejixianjin
				 * 12、并且写入：or_shop_fenpeiticheng 和 or_shop_userbasepay
				 * 13、再制作完整数据同时写入：or_shop_yejiticheng
				 **************************************************************/

				let addOrder = {
				 	order_sn: ordersn,
				 	guestid: data.gid,
				 	departmentid: shopid,
				 	recemoney: data.bala,
				 	operatorid: aid,
				 	auditorid: aid,
				 	status: 2,
				 	addtime: nowTime,
				 	ordertype: 3,
				 	remarks: data.remarks,
				 	fenpei: 1,
				 	gendanid: data.gdid
				}

				let orderid = await model.add(addOrder);

				if (!orderid) {
					await model.rollback();
					return this.fail('充值失败');
				}

				// 制作充值数据
				let addorder_one = [];
				if (data.bala*1) {
					addorder_one.push({
						orderid : orderid,
						departmentid: shopid,
						type: 4,
						typeid: data.level,
						typename: '充值金额',
						num: 1,
						price: data.bala,
						totalprice: data.bala*1,
						discount: 1,
						amount: data.bala*1,
						yejitype: 2,
						istemp: 0,
						isgift: 0,
						brandid: 0,
						usemoney: data.bala,
					})
				}
				if (data.gift*1) {
					addorder_one.push({
						orderid : orderid,
						departmentid: shopid,
						type: 5,
						typeid: data.level,
						typename: '赠送金额',
						num: 1,
						price: data.gift,
						totalprice: data.gift*1,
						discount: 1,
						amount: data.gift*1,
						yejitype: 2,
						istemp: 0,
						isgift: 0,
						brandid: 0,
						usemoney: 0,
					})
				}
				if (data.giftpx.length) {
					for(var j = 0, pxlen = data.giftpx.length; j < pxlen; j++){
						if (data.giftpx[j].id) {
							addorder_one.push({
								orderid : orderid,
								departmentid: shopid,
								type: data.giftpx[j].type,
								typeid: data.giftpx[j].id,
								typename: data.giftpx[j].name,
								num: data.giftpx[j].num,
								price: data.giftpx[j].price,
								totalprice: data.giftpx[j].price,
								discount: 0,
								amount: 0,
								yejitype: 2,
								istemp: 1,
								isgift: 1,
								brandid: data.giftpx[j].brandid,
								usemoney: 0,
							})
						}
					}
				}

				// 把制作的充值数据添加到订单附属表
				let addorderInfo = await this.model('or_shop_orderinfo').db(model.db()).addMany(addorder_one);

				if (!addorderInfo) {
					await model.rollback();
					return this.fail('写入余额品项等失败');
				}

				// 记录客户账户充值记录
				let guestAccountLog = {
					guestid: data.gid,
					shopid: shopid,
					ordertype: 'CZD',
					orderid: orderid,
					balance: data.bala,
					giftbalance: data.gift,
					addtime: nowTime,
					type: 1
				}

				let addGuestAccountLog = await this.model('or_shop_guest_accountlog').db(model.db()).add(guestAccountLog);

				// 如果有现金收益且当前分店有设置积分比则记录客户的积分日志
				if (data.bala*1 && basis.jifenpercent>0) {
					let guestScoreLog = {
						shopid: shopid,
						guestid: data.gid,
						type: 3,
						money: data.bala,
						jifen: Math.floor(data.bala*basis.jifenpercent),
						orderid: orderid,
						addtime: nowTime
					}
					let addGuestScoreLog = await this.model('or_shop_jifenlog').db(model.db()).add(guestScoreLog);
					if (!addGuestScoreLog) {
						await model.rollback();
						return this.fail('记录积分失败');
					}
				}

				// 更新客户信息（balance,giftbalance,level,arrivetime,score）
				let ginfo = await this.model('or_guest').db(model.db()).where({id: data.gid}).find();

				let guestInfo = {
					balance: Number(ginfo.balance + data.bala*1).toFixed(2),
					giftbalance: Number(ginfo.giftbalance + data.gift*1).toFixed(2),
					level: data.level,
					arrivetime: nowTime,
					score: Number(ginfo.score + data.bala * basis.jifenpercent).toFixed(0)
				}

				let updateGuestInfo = await this.model('or_guest').db(model.db()).where({id: data.gid}).update(guestInfo);

				if (!updateGuestInfo && !addGuestAccountLog) {
					await model.rollback();
					return this.fail('更新客户余额和积分信息失败');
				}

				// 如果存在赠送的品项，则把赠送的品项分别存入or_shop_guestcardsubject和or_shop_guest_temp_reserve表
				// 并且根据赠送的产品减去相应的库存，并记录库存流动日志
				if (data.giftpx.length) {
					let slist = [], glist = [];
					data.giftpx.forEach((v)=>{
						if (v.id && v.type === 1) {
							glist.push({
								guestid: data.gid,
								goodsid: v.id,
								price: v.price,
								num: v.num,
								nownum: v.num,
								orderid: orderid,
								shopid: shopid,
								addtime: nowTime,
								isgift: 1,
								brandid: v.brandid
							})
						} else if (v.id && v.type === 2) {
							slist.push({
								guestid: data.gid,
								subjectid: v.id,
								num: v.num,
								nownum: v.num,
								price: v.price,
								cardtype: 2,
								orderid: orderid,
								addtime: nowTime,
								shopid: shopid,
							})
						}
					})

					let addGuestCardSubject = 1, addTempReserve = 1, addDecreGoodsLog = 1, updateDecreGoodsRes = 1;
					if (slist.length) {
						addGuestCardSubject = await this.model('or_shop_guestcardsubject').db(model.db()).addMany(slist);
					}
					if (glist.length) {
						addTempReserve = await this.model('or_shop_guest_temp_reserve').db(model.db()).addMany(glist);
					}

					// 如果有赠送的产品，则减去产品相应的库存，如果库存不足则不能充值
					let decreGoods = [], decreGoodsLog = [];

					for (var i = data.giftpx.length - 1; i >= 0; i--) {
						if (data.giftpx[i].id && data.giftpx[i].type===1) {
							let shopGoods = await this.model('or_shop_goods').db(model.db()).where({shopid: shopid, goodsid: data.giftpx[i].id}).find();
							decreGoods.push({
								id: shopGoods.id,
								nums: shopGoods.nums - data.giftpx[i].num
							})
							if (shopGoods.nums - data.giftpx[i].num < 0) {
								await model.rollback();
								return this.fail('产品库存剩余数量不足')
							}

							decreGoodsLog.push({
								departmentid: shopid,
								goodsid: shopGoods.goodsid,
								ordertype: 'CZD',
								orderid: orderid,
								nums: -data.giftpx[i].num,
								addtime: nowTime,
								posttime: nowTime
							})
						}
					}
					if (decreGoods.length) {
						updateDecreGoodsRes = await this.model('or_shop_goods').db(model.db()).updateMany(decreGoods);
					}

					if (decreGoodsLog.length) {
						addDecreGoodsLog = await this.model('or_shop_goodslog').db(model.db()).addMany(decreGoodsLog);
					}

					if (!addGuestCardSubject && !addTempReserve && !updateDecreGoodsRes && !addDecreGoodsLog) {
						await model.rollback();
						return this.fail('处理赠送品项失败');
					}
				}

				// 判断是否有收款账户
				if (data.alist.length) {
					let increAcco = [], increAccoLog = [], increAccoRes = 1, increAccoLogRes = 1;
					for (var i = data.alist.length - 1; i >= 0; i--) {
						if (data.alist[i].id) {
							let accoInfo = await this.model('or_shop_account').db(model.db()).where({id: data.alist[i].id}).find();
							increAcco.push({
								id: data.alist[i].id,
								balance: Number(accoInfo.balance + data.alist[i].money*1).toFixed(2)
							})
							increAccoLog.push({
								departmentid: shopid,
								type: 1,
								accountid: data.alist[i].id,
								ordertype: 'CZD',
								orderid: orderid,
								money: data.alist[i].money,
								addtime: nowTime
							})
						}
					}
					if (increAcco.length) {
						increAccoRes = await this.model('or_shop_account').db(model.db()).updateMany(increAcco);
					}
					if (increAccoLog.length) {
						increAccoLogRes = await this.model('or_shop_accountlog').db(model.db()).addMany(increAccoLog);
					}
					if (!increAccoRes && !increAccoLogRes) {
						await model.rollback();
						return this.fail('收款失败');
					}
				}

				// 如果有业绩人员，则写入or_shop_yejixianjin表
				// 并且把分配的提成写入or_shop_fenpeiticheng表和or_shop_userbasepay表
				// 同时制作业绩分配和提成分配在一起的数据添加到or_shop_yejiticheng表
				if (data.ulist.length) {
					let xianjin = [], fenpei = [], basepay = [], ticheng = [], xjRes = 1, fpRes = 1, bpRes = 1, tcRes = 1;
					data.ulist.forEach((v)=>{
						if (v.id) {
							xianjin.push({
								orderid: orderid,
								feattype: 'CZD',
								shopid: shopid,
								feat: v.money*1,
								bumenid: v.bumenid,
								xiaozuid: v.xiaozuid,
								userid: v.id,
								addtime: nowTime
							})
							fenpei.push({
								orderid: orderid,
								ordertype: 3,
								userid: v.id,
								type: 1,
								yeji: v.money*1,
								tichengbi: Number((v.ticheng*1)/(v.money*1)).toFixed(2),
								money: v.ticheng*1,
								addtime: nowTime
							})
							basepay.push({
								userid: v.id,
								category: 2,
								type: 1,
								money: v.money*1,
								orderid: orderid,
								ordertype: 3,
								time: nowTime,
								addtime: nowTime
							})
							ticheng.push({
								shopid: shopid,
								orderid: orderid,
								ordertype: 'CZD',
								xianjinyeji: v.money*1,
								xianjinticheng: v.ticheng*1,
								userid: v.id,
								bumenid: v.bumenid,
								xiaozuid: v.xiaozuid,
								addtime: nowTime,
								guestid: data.gid,
							})
						}
					})
					if (xianjin.length) {
						xjRes = await this.model('or_shop_yejixianjin').db(model.db()).addMany(xianjin);
					}
					if (fenpei.length) {
						fpRes = await this.model('or_shop_fenpeiticheng').db(model.db()).addMany(fenpei);
						bpRes = await this.model('or_shop_userbasepay').db(model.db()).addMany(basepay);
					}
					if (ticheng.length) {
						tcRes = await this.model('or_shop_yejiticheng').db(model.db()).addMany(ticheng);
					}
					if (!xjRes && !fpRes && !tcRes) {
						await model.rollback();
						return this.fail('分配员工业绩提成失败');
					}
				}
				await model.commit()
				return this.success('充值成功');
			} catch (e) {
				console.log(e);
				await model.rollback();
				return this.fail('充值失败');
			}

		})
	}

	// 仅保存当前充值单
	async onlysaveorderAction(){
		let data = JSON.parse(this.post('data'));

		let shopid = this.shop_userinfo.departmentid;

		let aid = this.shop_userinfo.id;

		let nowTime = Math.round(Date.now()/1000);

		let ordersn = await this.getordersn('CZD',1);

		let model = this.model('or_shop_order');

		await model.transaction(async ()=>{
			try {

				let addorder = {
					'order_sn': ordersn,
					'guestid' : data.gid,
					'departmentid' : shopid,
					'recemoney' : data.bala*1,
					'ordertype' : 3,
					'operatorid': aid,
					'addtime': nowTime,
					'remarks':data.remarks,
					'gendanid': data.gdid
				}
				let orderid = await this.model('or_shop_order').db(model.db()).add(addorder);

				if (!orderid) {
					await model.rollback();
					return this.fail('保存失败');
				}
				
				let addorder_one = [];
				if (data.bala*1) {
					addorder_one.push({
						orderid : orderid,
						departmentid: shopid,
						type: 4,
						typeid: data.level,
						typename: '充值金额',
						num: 1,
						price: data.bala,
						totalprice: data.bala*1,
						discount: 1,
						amount: data.bala*1,
						yejitype: 2,
						istemp: 0,
						isgift: 0,
						brandid: 0,
					})
				}
				if (data.gift*1) {
					addorder_one.push({
						orderid : orderid,
						departmentid: shopid,
						type: 5,
						typeid: data.level,
						typename: '赠送金额',
						num: 1,
						price: data.gift,
						totalprice: data.gift*1,
						discount: 1,
						amount: data.gift*1,
						yejitype: 2,
						istemp: 0,
						isgift: 0,
						brandid: 0,
					})
				}
				let addorder_two = [];
				if (data.giftpx.length) {
					for(var j = 0, pxlen = data.giftpx.length; j < pxlen; j++){
						if (data.giftpx[j].id) {
							addorder_two.push({
								orderid : orderid,
								departmentid: shopid,
								type: data.giftpx[j].type,
								typeid: data.giftpx[j].id,
								typename: data.giftpx[j].name,
								num: data.giftpx[j].num,
								price: data.giftpx[j].price,
								totalprice: data.giftpx[j].price,
								discount: 0,
								amount: 0,
								yejitype: 2,
								istemp: 1,
								isgift: 1,
								brandid: data.giftpx[j].brandid,
							})
						}
					}
				}
				let addorder_three = addorder_one.concat(addorder_two);
				let addorder_four = await this.model('or_shop_orderinfo').db(model.db()).addMany(addorder_three);

				if(!addorder_four){
					await model.rollback();
					return this.fail('充值失败')
				}

				await model.commit();
				return this.success('保存成功')

			} catch (e) {
				console.log(e);
				await model.rollback();
				return this.fail('保存失败');
			}
		})
	}

	// 获取充值单信息
	async getoinfoAction(){
		let oid = this.get('oid');

		let shopid = this.shop_userinfo.departmentid;

		let oInfo = await this.model('or_shop_order')
				.alias('o')
				.field('o.*,u.name')
				.join('`think_or_app_user` u on o.gendanid=u.id')
				.where({'o.id': oid})
				.find();

		let gInfo = await this.model('or_guest')
				.alias('g')
				.field('g.*,v.vipname')
				.join('`think_or_guest_vipgrade` v on v.id=g.level')
				.where({'g.id': oInfo.guestid})
				.find();

		let oList = await this.model('or_shop_orderinfo').where({departmentid: shopid, orderid: oid}).select();

		let data = {
			oInfo: oInfo,
			gInfo: gInfo,
			oList: oList,
		}

		let aList = [], uList = [], tList = [];
		if (oInfo.status > -1) {
			aList = await this.model('or_shop_accountlog')
			.alias('l')
			.field('l.money, a.id, a.name')
			.join('`think_or_shop_account` a on a.id=l.accountid')
			.where({'l.departmentid': shopid, 'l.ordertype': 'CZD', 'l.orderid': oid})
			.select();

			uList = await this.model('or_shop_yejiticheng')
			.alias('t')
			.field('t.id,t.addtype,t.xianjinyeji,t.userid,u.name,u.bumenid,u.xiaozuid')
			.join('`think_or_app_user` u on u.id=t.userid')
			.where({'t.shopid': shopid, 't.orderid': oid, 't.ordertype': 'CZD'})
			.select();

			data.aList = aList || [];
			data.uList = uList || [];
			if (oInfo.status > 0) {
				tList = await this.model('or_shop_yejiticheng')
				.alias('t')
				.field('t.id,t.addtype,t.xianjinyeji,IF(t.addtype>0,t.qitaticheng,t.xianjinticheng) as xianjinticheng,t.userid,u.name')
				.join('`think_or_app_user` u on u.id=t.userid')
				.where({'t.shopid': shopid, 't.orderid': oid, 't.ordertype': 'CZD'})
				.select();

				data.tList = tList || [];
			}
		}

		return this.json(data);
	}

	/************************** 充值流程 ************************/
	// 保存并编辑订单
	async gooneAction(){
		let data = JSON.parse(this.post('data'));

		let shopid = this.shop_userinfo.departmentid;

		let aid = this.shop_userinfo.id;

		if (data.oid) {
			let zt = await this.model('or_shop_order').where({id: data.oid}).find();
			if (zt.status > 0) {
				return this.fail('当前订单已经结账');
			}
		}

		let time = Math.round(Date.now()/1000);
		let ordersn
		if (!data.oid) {
			ordersn = await this.getordersn('CZD',1);
		}

		let model = this.model('or_shop_order');

		await model.transaction(async ()=>{

			try {
				let orderid = 0;
				if (data.oid) {
					let gxOinfoOne = await model.where({id: data.oid}).update({
								recemoney: data.bala*1,
								operatorid: aid,
								remarks: data.remarks,
								gendanid: data.gdid,
								iscross: data.crossShop
							})

					let delOinfoList = await this.model('or_shop_orderinfo').db(model.db()).where({departmentid: shopid, orderid: data.oid}).delete();

					let adOinfoOne = [];
					if (data.bala*1) {
						adOinfoOne.push({
							orderid : data.oid,
							departmentid: shopid,
							type: 4,
							typeid: data.level,
							typename: '充值金额',
							num: 1,
							price: data.bala,
							totalprice: data.bala*1,
							discount: 1,
							amount: data.bala*1,
							yejitype: 2,
							istemp: 0,
							usemoney: data.bala*1,
							isgift: 0,
							brandid: 0,
						})
					}
					if (data.gift*1) {
						adOinfoOne.push({
							orderid : data.oid,
							departmentid: shopid,
							type: 5,
							typeid: data.level,
							typename: '赠送金额',
							num: 1,
							price: data.gift,
							totalprice: data.gift*1,
							discount: 1,
							amount: data.gift*1,
							yejitype: 2,
							istemp: 0,
							usemoney: 0,
							isgift: 0,
							brandid: 0,
						})
					}
					if (data.giftpx.length) {
						for(var j = 0, pxlen = data.giftpx.length; j < pxlen; j++){
							if (data.giftpx[j].id) {
								adOinfoOne.push({
									orderid : data.oid,
									departmentid: shopid,
									type: data.giftpx[j].type,
									typeid: data.giftpx[j].id,
									typename: data.giftpx[j].name,
									num: data.giftpx[j].num,
									price: data.giftpx[j].price,
									totalprice: data.giftpx[j].price,
									discount: 0,
									amount: 0,
									yejitype: 2,
									istemp: 1,
									usemoney: 0,
									isgift: 1,
									brandid: data.giftpx[j].brandid,
								})
							}
						}
					}

					let adOinfoRes = await this.model('or_shop_orderinfo').db(model.db()).addMany(adOinfoOne);

					if (!gxOinfoOne && !delOinfoList && !adOinfoRes) {
						await model.rollback();
						return this.fail('保存失败');
					}
				} else {
					let addorder = {
						'order_sn': ordersn,
						'guestid' : data.gid,
						'departmentid' : shopid,
						'recemoney' : data.bala*1,
						'ordertype' : 3,
						'operatorid': aid,
						'addtime': time,
						'remarks':data.remarks,
						'gendanid': data.gdid,
						'iscross': data.crossShop
					}
					orderid = await model.add(addorder);

					let addorder_one = [];
					if (data.bala*1) {
						addorder_one.push({
							orderid : orderid,
							departmentid: shopid,
							type: 4,
							typeid: data.level,
							typename: '充值金额',
							num: 1,
							price: data.bala,
							totalprice: data.bala*1,
							discount: 1,
							amount: data.bala*1,
							yejitype: 2,
							istemp: 0,
							usemoney: data.bala*1,
							isgift: 0,
							brandid: 0,
						})
					}
					if (data.gift*1) {
						addorder_one.push({
							orderid : orderid,
							departmentid: shopid,
							type: 5,
							typeid: data.level,
							typename: '赠送金额',
							num: 1,
							price: data.gift,
							totalprice: data.gift*1,
							discount: 1,
							amount: data.gift*1,
							yejitype: 2,
							istemp: 0,
							usemoney: 0,
							isgift: 0,
							brandid: 0,
						})
					}
					if (data.giftpx.length) {
						for(var j = 0, pxlen = data.giftpx.length; j < pxlen; j++){
							if (data.giftpx[j].id) {
								addorder_one.push({
									orderid : orderid,
									departmentid: shopid,
									type: data.giftpx[j].type,
									typeid: data.giftpx[j].id,
									typename: data.giftpx[j].name,
									num: data.giftpx[j].num,
									price: data.giftpx[j].price,
									totalprice: data.giftpx[j].price,
									discount: 0,
									amount: 0,
									yejitype: 2,
									istemp: 1,
									usemoney: 0,
									isgift: 1,
									brandid: data.giftpx[j].brandid,
								})
							}
						}
					}

					let addorderRes = await this.model('or_shop_orderinfo').db(model.db()).addMany(addorder_one);

					if (!orderid && !addorderRes) {
						await model.rollback();
						return this.fail('保存失败');
					}
				}

				let saveRemarks = await this.model('or_guest').db(model.db()).where({id: data.gid}).update({remarks: data.gremarks});

				if (!saveRemarks) {
					await model.rollback();
					return this.fail('更新客户描述')
				}

				let oid = orderid?orderid:data.oid;

				await model.commit();
				return this.success({code: 200, info: '保存成功', orderid: oid, status: 0});

			} catch(e){
				console.log(e)
				await model.rollback();
				return this.fail('开单失败');
			}

		})
	}

	// 结账
	async gotwoAction(){
		let data = JSON.parse(this.post('data'));

		if (data.oid) {
			let zt = await this.model('or_shop_order').where({id: data.oid}).find();

			if (zt.status > 0) {
				return this.fail('当前订单已结账');
			}
		}

		let shopid = this.shop_userinfo.departmentid;

		let aid = this.shop_userinfo.departmentid;

		let basis = await this.model('or_shop_basis').where({shopid: shopid}).find();

		let time = Math.round(Date.now()/1000);

		let model = this.model('or_shop_order');

		await model.transaction(async ()=>{

			try {

				let oinfo = await model.where({id: data.oid}).find();

				let olist = await this.model('or_shop_orderinfo').db(model.db()).where({departmentid: shopid, orderid: data.oid}).select();

				let bala = 0, gift = 0, pxs = [], level = 0;
				olist.forEach((v)=>{
					if (v.type === 4) {
						bala = v.price;
						level = v.typeid;
					}
					if (v.type === 5) {
						gift = v.price;
						level = v.typeid;
					}
					if (v.type === 1 || v.type === 2) {
						pxs.push(v)
					}
				})

				// 记录客户账户充值记录
				let guestAccountLog = {
					guestid: oinfo.guestid,
					shopid: shopid,
					ordertype: 'CZD',
					orderid: data.oid,
					balance: bala,
					giftbalance: gift,
					addtime: oinfo.addtime,
					type: 1
				}

				let addGuestAccountLog = await this.model('or_shop_guest_accountlog').db(model.db()).add(guestAccountLog);

				// 如果有现金收益且当前分店有设置积分比则记录客户的积分日志
				if (bala && basis.jifenpercent && basis.jifenpercent > 0) {
					let guestScoreLog = {
								shopid: shopid,
								guestid: oinfo.guestid,
								type: 3,
								money: bala,
								jifen: Math.floor(bala*basis.jifenpercent),
								orderid: data.oid,
								addtime: oinfo.addtime
							}
					let addGuestScoreLog = await this.model('or_shop_jifenlog').db(model.db()).add(guestScoreLog);
					if (!addGuestScoreLog) {
						await model.rollback();
						return this.fail('记录积分失败');
					}
				}

				// 更新客户信息（balance,giftbalance,level,arrivetime,score）
				let ginfo = await this.model('or_guest').db(model.db()).where({id: oinfo.guestid}).find();

				let guestInfo = {
							balance: Number(ginfo.balance + bala).toFixed(2),
							giftbalance: Number(ginfo.giftbalance + gift).toFixed(2),
							level: level,
							arrivetime: oinfo.addtime,
							score: Number(ginfo.score + bala * basis.jifenpercent).toFixed(0)
						}

				let updateGuestInfo = await this.model('or_guest').db(model.db()).where({id: oinfo.guestid}).update(guestInfo);

				if (!updateGuestInfo && !addGuestAccountLog) {
					await model.rollback();
					return this.fail('更新客户余额和积分信息失败');
				}

				// 如果存在赠送的品项，则把赠送的品项分别存入or_shop_guestcardsubject和or_shop_guest_temp_reserve表
				// 并且根据赠送的产品减去相应的库存，并记录库存流动日志
				if (pxs.length) {
					let slist = [], glist = [];
					pxs.forEach((v)=>{
						if (v.id && v.type === 1) {
							glist.push({
								guestid: oinfo.guestid,
								goodsid: v.typeid,
								price: v.price,
								num: v.num,
								nownum: v.num,
								orderid: data.oid,
								shopid: shopid,
								addtime: oinfo.addtime,
								isgift: 1,
								brandid: v.brandid
							})
						} else if (v.id && v.type === 2) {
							slist.push({
								guestid: oinfo.guestid,
								subjectid: v.typeid,
								num: v.num,
								nownum: v.num,
								price: v.price,
								cardtype: 2,
								orderid: data.oid,
								addtime: oinfo.addtime,
								shopid: shopid,
							})
						}
					})

					let addGuestCardSubject = 1, addTempReserve = 1, addDecreGoodsLog = 1, updateDecreGoodsRes = 1;
					if (slist.length) {
						addGuestCardSubject = await this.model('or_shop_guestcardsubject').db(model.db()).addMany(slist);
					}

					// 如果有赠送的产品，则减去产品相应的库存，如果库存不足则不能充值
					
					if (glist.length) {
						addTempReserve = await this.model('or_shop_guest_temp_reserve').db(model.db()).addMany(glist);

						let decreGoods = [], decreGoodsLog = [];
						for (var i = glist.length - 1; i >= 0; i--) {

								let shopGoods = await this.model('or_shop_goods').db(model.db()).where({shopid: shopid, goodsid: glist[i].goodsid}).find();

								decreGoods.push({
									id: shopGoods.id,
									nums: shopGoods.nums - glist[i].num
								})

								if (shopGoods.nums - glist[i].num < 0) {
									await model.rollback();
									return this.fail('产品库存剩余数量不足')
								}

								decreGoodsLog.push({
									departmentid: shopid,
									goodsid: glist[i].goodsid,
									ordertype: 'CZD',
									orderid: data.oid,
									nums: -glist[i].num,
									addtime: oinfo.addtime,
									posttime: oinfo.addtime
								})

						}

						if (decreGoods.length) {
							updateDecreGoodsRes = await this.model('or_shop_goods').db(model.db()).updateMany(decreGoods);
						}

						if (decreGoodsLog.length) {
							addDecreGoodsLog = await this.model('or_shop_goodslog').db(model.db()).addMany(decreGoodsLog);
						}
					}

					if (!addGuestCardSubject && !addTempReserve && !updateDecreGoodsRes && !addDecreGoodsLog) {
						await model.rollback();
						return this.fail('处理赠送品项失败');
					}
				}

				// 如果有现金收益则增加收款帐号并记录收款金额
				if (data.alist.length) {
					let upAcco = [], adAccoLogs = [];
					for (var i = data.alist.length - 1; i >= 0; i--) {
						let aco = await this.model('or_shop_account').db(model.db()).where({id: data.alist[i].id}).find()

						upAcco.push({
							id: data.alist[i].id,
							balance: aco.balance + data.alist[i].money*1
						})

						adAccoLogs.push({
							departmentid: shopid,
							type: 1,
							accountid: data.alist[i].id,
							ordertype: 'CZD',
							orderid: data.oid,
							money: data.alist[i].money,
							addtime: oinfo.addtime
						})
					}

					let upAcoRes = await this.model('or_shop_account').db(model.db()).updateMany(upAcco);

					let adAcoRes = await this.model('or_shop_accountlog').db(model.db()).addMany(adAccoLogs);

					if (!upAcoRes && !adAcoRes) {
						await model.rollback();
						return this.fail('收款失败');
					}
				}

				// 如果有业绩分配人员，则记录
				if (data.ulist.length) {
					let adxjLogs = [], adtcLogs = [];
					data.ulist.forEach((v)=>{
						adxjLogs.push({
							orderid: data.oid,
							feattype: 'CZD',
							shopid: shopid,
							feat: v.money,
							bumenid: v.bumenid,
							xiaozuid: v.xiaozuid,
							userid: v.id,
							addtime: oinfo.addtime
						})

						adtcLogs.push({
							shopid: shopid,
							orderid: data.oid,
							ordertype: 'CZD',
							xianjinyeji: v.money,
							userid: v.id,
							bumenid: v.bumenid,
							xiaozuid: v.xiaozuid,
							addtime: oinfo.addtime,
							guestid: oinfo.guestid
						})
					})

					let adxjLogRes = await this.model('or_shop_yejixianjin').db(model.db()).addMany(adxjLogs);

					let adtcLogRes = await this.model('or_shop_yejiticheng').db(model.db()).addMany(adtcLogs);

					if (!adxjLogRes && !adtcLogRes) {
						await model.rollback();
						return this.fail('分配业绩失败');
					}
				}

				let res = await model.where({id: data.oid}).update({
					status: 1,
					auditorid: aid,
					gendanid: data.gdid*1
				})

				if (!res) {
					await model.rollback();
					return this.fail('结账失败');
				}

				await model.commit();
				return this.success({code: 200, info: '结账成功', status: 1});

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('结账失败');
			}

		})
	}

	// 重新分配充值现金业绩
	async resetfenpeiAction(){
		let data = JSON.parse(this.post('data'));

		let oinfo = await this.model('or_shop_order').where({id: data.oid}).find();

		let isCanEditOrder = await this.isCanEditOrder(data.oid, 'CZD')
		if (!isCanEditOrder) {
			return this.fail('暂不允许操作其他店单据！')
		}

		if (oinfo.status > 1) {
			return this.fail('当前订单已经分配业绩提成');
		}

		if (!data.ulist.length) {
			return this.fail('分配业绩人员为空');
		}

		let shopid = this.shop_userinfo.departmentid;

		let model = this.model('or_shop_yejiticheng');

		await model.transaction(async ()=>{

			try {

				let yejiLogs = await model.where({shopid: shopid, orderid: data.oid, ordertype: 'CZD'}).select();

				if (yejiLogs.length) {
					let clearTcLogs = await model.where({shopid: shopid, orderid: data.oid, ordertype: 'CZD'}).delete()
					let clearYjLogs = await this.model('or_shop_yejixianjin').db(model.db()).where({orderid: data.oid, feattype: 'CZD', shopid: shopid}).delete();

					if (!clearTcLogs && !clearYjLogs) {
						await model.rollback();
						return this.fail('清除之前业绩失败');
					}
				}

				if (data.ulist.length) {
					let adYjLogs = [], adTcLogs = [];
					data.ulist.forEach((v)=>{
						adYjLogs.push({
							orderid: data.oid,
							feattype: 'CZD',
							shopid: shopid,
							feat: v.money*1,
							bumenid: v.bumenid,
							xiaozuid: v.xiaozuid,
							userid: v.id,
							addtime: oinfo.addtime
						})
						adTcLogs.push({
							shopid: shopid,
							orderid: data.oid,
							ordertype: 'CZD',
							xianjinyeji: v.money*1,
							userid: v.id,
							bumenid: v.bumenid,
							xiaozuid: v.xiaozuid,
							addtime: oinfo.addtime,
							guestid: oinfo.guestid
						})
					})

					let adYjLogsRes = await this.model('or_shop_yejixianjin').db(model.db()).addMany(adYjLogs);

					let adTcLogsRes = await model.addMany(adTcLogs);

					if (!adYjLogsRes && !adTcLogsRes) {
						await model.rollback();
						return this.fail('重新分配失败');
					}
				}

				await model.commit();
				return this.success({code: 200, info: '分配成功'});

			} catch (e) {
				console.log(e)
				await model.rollback();
				return this.fail('重新分配业绩失败');
			}

		})
	}

	// 完成充值流程
	async rechargeFinishAction(){
		let data = JSON.parse(this.post('retData'));

		let oinfo = await this.model('or_shop_order').where({id: data.oid}).find();

		let isCanEditOrder = await this.isCanEditOrder(data.oid, 'CZD')
		if (!isCanEditOrder) {
			return this.fail('暂不允许操作其他店单据！')
		}

		if (oinfo.status > 1) {
			return this.fail('当前订单已经分配业绩提成')
		}

		let shopid = this.shop_userinfo.departmentid;

		let aid = this.shop_userinfo.id;

		let time = Math.round(Date.now()/1000);

		let model = this.model('or_shop_order');

		await model.transaction(async ()=>{

			try {

				/*
				* 1、先判断yejiticheng表是否有数据，如果有就先删除
				* 2、然后在重新添加新的提成信息，把业绩和提成都加入
				*/

				let tcList = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: data.oid, ordertype: 'CZD'}).select();

				if (!think.isEmpty(tcList)) {
					let delTcListRes = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: data.oid, ordertype: 'CZD'}).delete();
					if (!delTcListRes) {
						await model.rollback();
						return this.fail('删除缓存数据失败');
					}
				}

				if (data.tclist.length) {
					let geng = [], addFenPei = [], addTiCheng = [], addPay = [];
					data.tclist.forEach((v)=>{

						addTiCheng.push({
							shopid: shopid,
							orderid: data.oid,
							ordertype: 'CZD',
							addtype: v.addtype,
							xianjinyeji: v.money*1,
							xianjinticheng: v.addtype==0?v.ticheng*1:0,
							qitaticheng: v.addtype==1?v.ticheng*1:0,
							userid: v.id,
							bumenid: v.bumenid,
							xiaozuid: v.xiaozuid,
							addtime: oinfo.addtime,
							guestid: oinfo.guestid
						})

						if (!v.addtype) {
							addFenPei.push({
								orderid: data.oid,
								ordertype: 3,
								userid: v.id,
								type: 1,
								yeji: v.money*1,
								tichengbi: Number(v.ticheng/v.money).toFixed(2),
								money: v.ticheng,
								addtime: oinfo.addtime
							})
						}

						if (v.addtype) {
							addPay.push({
								userid: v.id,
								category: 2,
								type: 4,
								money: v.ticheng,
								orderid: data.oid,
								ordertype: 3,
								time: oinfo.addtime,
								addtime: time
							})
						} else {
							addPay.push({
								userid: v.id,
								category: 2,
								type: 1,
								money: v.ticheng,
								orderid: data.oid,
								ordertype: 3,
								time: oinfo.addtime,
								addtime: time
							})
						}
					})

					if (geng.length) {
						let upTcRes = await this.model('or_shop_yejiticheng').db(model.db()).updateMany(geng);
						if (!upTcRes) {
							await model.rollback();
							return this.fail('更新业绩提成失败');
						}
					}
					if (addFenPei.length) {
						let adFpRes = await this.model('or_shop_fenpeiticheng').db(model.db()).addMany(addFenPei);
						if (!adFpRes) {
							await model.rollback();
							return this.fail('添加分配提成失败');
						}
					}
					if (addTiCheng.length) {
						let adTcRes = await this.model('or_shop_yejiticheng').db(model.db()).addMany(addTiCheng);
						if (!adTcRes) {
							await model.rollback();
							return this.fail('添加业绩提成失败');
						}
					}
					if (addPay.length) {
						let adPyRes = await this.model('or_shop_userbasepay').db(model.db()).addMany(addPay);
						if (!adPyRes) {
							await model.rollback();
							return this.fail('添加员工工资提成失败');
						}
					}
				}

				let fin = await model.where({id: data.oid}).update({status: 2, auditorid: aid});

				if (!fin) {
					await model.rollback();
					return this.fail('更改订单状态失败');
				}
				await model.commit();
				return this.success('充值完成');

			} catch (e) {
				console.log(e)
				await model.rollback();
				return this.fail('提成分配失败');
			}

		})
	}

	// 已分配提成重新分配（反分配）
	async fanfenpeiAction(){
		let id = this.post('id');

		////////////////////////////////////////////////////////////////////////
		// 1、只删除分配的提成																								//
		// 2、先删除or_shop_fenpeiticheng 和 or_shop_userbasepay里分配的提成	//
		// 3、先更新or_shop_yejiticheng表，把里面addtype为0的行现金提成变为0	//
		// 		然后再把addtype为1的行删除																			//
		// 4、最后把订单的已分配提成状态改为已结账														//
		////////////////////////////////////////////////////////////////////////

		let oinfo = await this.model('or_shop_order').where({id: id}).find();

		let isCanEditOrder = await this.isCanEditOrder(id, 'CZD')
		if (!isCanEditOrder) {
			return this.fail('暂不允许操作其他店单据！')
		}
		if (oinfo.status < 2) {
			return this.fail('当前订单未分配提成')
		}

		let shopid = this.shop_userinfo.departmentid;

		let model = this.model('or_shop_order');

		await model.transaction(async ()=>{

			try {

				let tcOne = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: id, ordertype: 'CZD', addtype: 0}).select();

				let tcTwo = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: id, ordertype: 'CZD', addtype: 1}).select();

				let delTcRes = 1, upOneRes = 1, delPayRes = 1, delFpRes = 1;

				if (tcTwo.length) {
					delTcRes = await this.model('or_shop_yejiticheng').db(model.db()).where({shopid: shopid, orderid: id, ordertype: 'CZD', addtype: 1}).delete();
				}

				if (tcOne.length) {
					let upOne = [];
					tcOne.forEach((v)=>{
						upOne.push({
							id: v.id,
							xianjinticheng: 0
						})
					})
					upOneRes = await this.model('or_shop_yejiticheng').db(model.db()).updateMany(upOne);

					delPayRes = await this.model('or_shop_userbasepay').db(model.db()).where({category: 2, orderid: id, ordertype: 3}).delete();

					delFpRes = await this.model('or_shop_fenpeiticheng').db(model.db()).where({orderid: id, ordertype: 3, type: 1}).delete();
				}

				if (!delTcRes && !upOneRes && !delPayRes && !delFpRes) {
					await model.rollback();
					return this.fail('反提成分配失败')
				}

				let zt = await model.where({id: id}).update({status: 1});

				if (!zt) {
					await model.rollback();
					return this.fail('更改订单状态失败');
				}
				await model.commit();
				return this.success({code: 200, info: '反分配提成成功', status: 1});

			} catch(e) {
				console.log(e);
				await model.rollback();
				return this.fail('反分配失败');
			}
		})
	}


}